package com.xtedu.examproject.controller;

import com.xtedu.examproject.entity.ExamQuestion;
import com.xtedu.examproject.entity.ExamQuestionRelation;
import com.xtedu.examproject.entity.TemplateDetail;
import com.xtedu.examproject.service.ExamQuestionRelaService;
import com.xtedu.examproject.service.ExamQuestionService;
import com.xtedu.examproject.service.ExaminationService;
import com.xtedu.examproject.service.TemplateDetailService;
import com.xtedu.examproject.util.CommonUtils;
import com.xtedu.examproject.util.RedisUtil;
import com.xtedu.examproject.util.UploadUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * Author: xzy
 * Date: 2025/10/16
 * Last Modified by: xzy
 * Last Modified date: 2025/10/16
 * Description: TODO - Add file description here
 */
@WebServlet("/examquestionrela/*")
public class ExamQuestionRelaServlet extends HttpServlet {

    private ExamQuestionRelaService examQuestionRelaService;
    private ExaminationService examinationService;
    private TemplateDetailService templateDetailService;
    private ExamQuestionService examQuestionService;

    @Override
    public void init() throws ServletException {
        examQuestionRelaService = new ExamQuestionRelaService();
        examinationService = new ExaminationService();
        examQuestionService = new ExamQuestionService();
        templateDetailService = new TemplateDetailService();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo = req.getPathInfo();

        // 处理 null 或空路径
        if (pathInfo == null || pathInfo.equals("/") || pathInfo.isEmpty()) {
            CommonUtils.sendErrorResponse(resp, "Invalid path");
            return;
        }

        // 标准化路径（去除前导和尾随斜杠）
        String path = pathInfo.replaceAll("^/|/$", "");

        switch (path) {
            case "findById" -> findById(req, resp);
            case "findByExamId" -> findByExamId(req, resp);
        }
    }

    private void findById(HttpServletRequest req, HttpServletResponse resp) {
        int id = Integer.parseInt(req.getParameter("id"));
        try {
            ExamQuestionRelation eqr = examQuestionRelaService.findById(id);
            if (eqr == null) {
                CommonUtils.sendErrorResponse(resp, "未找到该数据");
                return;
            }
            CommonUtils.sendSuccessResponse(resp, "查询成功", eqr);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private void findByExamId(HttpServletRequest req, HttpServletResponse resp) {
        int examId = Integer.parseInt(req.getParameter("examId"));
        try {
            List<ExamQuestion> eqr = examQuestionRelaService.findByExamId(examId);
            if (eqr == null) {
                CommonUtils.sendErrorResponse(resp, "未找到该数据");
                return;
            }
            CommonUtils.sendSuccessResponse(resp, "查询成功", eqr);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo = req.getPathInfo();

        // 标准化路径（去除前导和尾随斜杠）
        String path = pathInfo.replaceAll("^/|/$", "");

        switch (path) {
            case "add" -> add(req, resp);
            case "update" -> update(req, resp);
            case "delete" -> delete(req, resp);
            case "upload" -> UploadUtil.uploadFile(req, resp);
            case "autoGenerate" -> autoGenerate(req, resp);
            case "manualGenerate" -> manualGenerate(req, resp);
        }
    }

    /**
     * 自动组卷
     *
     * @param req  请求
     * @param resp 响应
     */
    private void autoGenerate(HttpServletRequest req, HttpServletResponse resp) {
        try {
            // 1. 拿到模板ID
            int templateId = Integer.parseInt(req.getParameter("templateId"));
            int examId = Integer.parseInt(req.getParameter("examId"));
            // 2. 根据模板ID拿到所有题型数量信息
            List<TemplateDetail> templateDetails = templateDetailService.findByTemplateId(templateId);
            // 3. 根据题型数量信息从题库里随机抽题，添加到试卷里
            List<ExamQuestion> examquestionList = new ArrayList<>();
            templateDetails.forEach(templateDetail -> {
                System.out.println(templateDetail);
                Integer questionTypeId = templateDetail.getQuestionTypeId();
                Integer questionCount = templateDetail.getQuestionCount();
                int courseId = examinationService.findCourseIdByExamId(examId);
                List<ExamQuestion> examQuestions = examQuestionService.randomQuestions(courseId, questionTypeId, questionCount);
                examquestionList.addAll(examQuestions);
            });

            // 4. 同时往exam_question表插入试卷数据 mysql
            examquestionList.forEach(examQuestion -> {
                examQuestionRelaService.insert(examId, examQuestion.getId());
            });
            // 5. 返回试卷信息（一个集合）存到Redis
            RedisUtil.setObject("examPaper:" + examId, examquestionList);
            RedisUtil.expire("examPaper:" + examId, 60 * 60 * 24);

            if (examquestionList.isEmpty()) {
                CommonUtils.sendErrorResponse(resp, "生成失败或没有该数据");
                return;
            }
            CommonUtils.sendSuccessResponse(resp, "生成成功", examquestionList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void manualGenerate(HttpServletRequest req, HttpServletResponse resp) {
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) {
        try {
            ExamQuestionRelation eqr = CommonUtils.getFormDataFromRequest(req, ExamQuestionRelation.class);
            int result = examQuestionRelaService.insert(eqr);
            if (result <= 0) {
                CommonUtils.sendErrorResponse(resp, "添加失败");
                return;
            }
            CommonUtils.sendSuccessResponse(resp, "添加成功", null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) {
        try {
            ExamQuestionRelation eqr = CommonUtils.getFormDataFromRequest(req, ExamQuestionRelation.class);
            int result = examQuestionRelaService.update(eqr);
            if (result <= 0) {
                CommonUtils.sendErrorResponse(resp, "更新失败");
                return;
            }
            CommonUtils.sendSuccessResponse(resp, "更新成功", null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) {
        try {
            int id = Integer.parseInt(req.getParameter("id"));
            int result = examQuestionRelaService.deleteById(id);
            if (result <= 0) {
                CommonUtils.sendErrorResponse(resp, "删除失败");
                return;
            }
            CommonUtils.sendSuccessResponse(resp, "删除成功", null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}
